/**
 * Description: IO多路复用 select 实现
 * File:client_read |Time: 2021-07-19 21:12
 */


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/select.h>
#include <sys/time.h>


#define BUFSIZE 128

#define ERR(msg) do {   \
    perror(msg);    \
    printf("err_at: %s:%s %d\n", __FILE__, __func__, __LINE__); \
} while(0)

int main(int argc, const char *argv[])
{
    int ret, i, maxfd;
    char buf[BUFSIZE] = {0};
    int fd = open("/dev/demo_dev", O_RDWR);
    if (fd < 0) 
    {
        ERR("open");
        return -1;
    }


    fd_set fds;
    FD_ZERO( &fds );
    maxfd = fd;
    
    while (1)
    {
        FD_SET(fd, &fds);
        FD_SET(0, &fds);

        ret = select(maxfd + 1, &fds, NULL, NULL, NULL);
        if (ret < 0) 
        {
            ERR("select");
            return -1;
        }

        for (i = 0; i < maxfd + 1; i++) 
        {
            if (i == fd && FD_ISSET(fd, &fds) ) 
            {
                memset(buf, 0, sizeof(buf));
                printf("read from /dev/demo_dev");
                ret = read(fd, buf, sizeof(buf));
                if (ret < 0) 
                {
                    ERR("read");
                    return -1;
                }

                printf("read res = %s\n", buf);
            }

            if (i == 0 && FD_ISSET(0, &fds) ) 
            {
                memset(buf, 0, sizeof(buf));
                printf("read from stdin\n");
                ;
                if (fgets(buf, BUFSIZE, stdin) == NULL) 
                {
                    ERR("fgets");
                    return -1;
                }

                printf("user input: %s\n", buf);    
            }

        }

    }

    if (close(fd) < 0) 
    {
        ERR("close");
        return -1;
    }

    return 0;
}


